import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Button,
    Modal,
    message
} from 'antd';
 import AdAddressList from '../../../components/Operation/adaddress';
import AdAddressEdit from '../../../components/Operation/adaddress/AdAddressEdit';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import styles from './AdAddress.less'
import {powerControl} from '../../../utils/powerControl';
const AuthButton = powerControl(Button);

const FormItem = Form.Item;
const {Option} = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(state => ({
    rule: state.adAddress
 }))
@Form.create()
export default class AdAddress extends PureComponent{

    state = {
        modalVisible: false,
        editType: 'add',
        formValues: {},
        record: {},
        selectedRows: [],
    };

    componentDidMount(){
        const {dispatch} = this.props;
        dispatch({
            type: 'adAddress/fetch',
        });
    }

    handleAddType = () => {
        this.handleModalVisible(true);
        this.setState({
            editType: 'add',
        });
    }

    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
        });
    }

    handleModalSuccess = (pagination) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;
        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
        };
        dispatch({
            type: 'adAddress/fetch',
            payload: params,
        });
    }

    handleYyDetailUrlListChange = (pagination, filtersArg, sorter) => {
        const {dispatch} = this.props;
        const {formValues} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) => {
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues,
            ...filters,
        };
        if (sorter.field) {
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'adAddress/fetch',
            payload: params,
        });
    }

    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        dispatch({
            type: 'adAddress/fetch',
            payload: {},
        });
        this.setState({
            formValues: {},
        });
    }

    handleSearch = (e) => {
        e.preventDefault();

        const {dispatch, form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err) return;

            const values = {
                ...fieldsValue,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };

            this.setState({
                formValues: values,
            });

            dispatch({
                type: 'adAddress/fetch',
                payload: values,
            });
        });
    }

    handleAdd = () => {
        this.props.dispatch({
            type: 'adAddress/add',
            payload: {
                description: this.state.addInputValue,
            },
        });
        message.success('添加成功');
        this.setState({
            modalVisible: false,
        });
    }

    handleEditTypeRow = (record, pagination) => {
        this.handleModalVisible(true);
        this.setState({
            editType: 'mod',
            record: record
        });
    }

    handleDelTypeRow = (du_id, pagination) => {
        const {dispatch} = this.props;
        dispatch({
            type: 'adAddress/del',
            payload: {du_id: du_id},
            callback: (response) => {
                if (response.result === 0) {
                    message.success('删除成功');
                    this.handleModalSuccess(pagination);
                } else {
                    message.success('删除失败');
                }
            }
        });
    }

    handleSelectRows = (rows) => {
        this.setState({
            selectedRows: rows,
        });
    }

    renderSimpleForm() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="转入地址的备注">
                            {getFieldDecorator('remark')(
                                <Input placeholder="请输入"/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="状态">
                            {getFieldDecorator('status')(
                                <Select placeholder="请选择" style={{width: '100%'}}>
                                    <Option value="">请选择</Option>
                                    <Option value="0">不在用</Option>
                                    <Option value="1">在用</Option>
                                </Select>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <span className={styles.sumbitButtons}>
                          <AuthButton auth="adAddress.search" type="primary" htmlType="submit">查询</AuthButton>
                          <AuthButton auth="adAddress.reset" style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</AuthButton>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    renderForm() {
        return this.renderSimpleForm();
    }

    render() {
        const {modalVisible,editType,record,selectedRows} = this.state;
        const {rule: {loading: ruleLoading, data, typesSList}} = this.props;
        return (
            <PageHeaderLayout title="广告推荐转入地址">
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderForm()}
                        </div>
                        <div className={styles.tableListOperator}>
                            <AuthButton auth="adAddress.new" icon="plus" type="primary" onClick={() => this.handleAddType()}>新建</AuthButton>
                        </div>
                        <AdAddressList
                            selectedRows={selectedRows}
                            loading={ruleLoading}
                            data={data}
                            onSelectRow={this.handleSelectRows}
                            onChange={this.handleYyDetailUrlListChange}
                            onDelRow={this.handleDelTypeRow}
                            onEditRow={this.handleEditTypeRow}
                        />
                    </div>
                </Card>
                <Modal
                    title="新增广告推荐转入地址"
                    key={new Date()}
                    visible={modalVisible}
                    onOk={this.handleAdd}
                    onCancel={() => this.handleModalVisible()}
                    footer={null}
                >
                    <AdAddressEdit  ref="adAddressEdit"
                                   pagination={data.pagination}
                                   editType={editType}
                                   record={record}
                                   categorySList={typesSList}
                                   handleModalVisible={this.handleModalVisible}
                                   handleModalSuccess={this.handleModalSuccess}/>
                </Modal>
            </PageHeaderLayout>
        );
    }
}